package com.example.home.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.example.home.R;
import com.example.home.bean.Content;
import com.example.home.bean.MeBean;
import com.example.home.bean.PersonInfoUser;
import com.example.home.me.ChangePasswordActivity;
import com.example.home.me.FeedBackActivity;
import com.example.home.me.LoginActivity;
import com.example.home.me.MeInfoActivity;
import com.example.home.me.OrderListActivity;
import com.example.home.tool.OKHttpTool;
import com.google.gson.Gson;

import org.json.JSONObject;

import okhttp3.Request;
import okhttp3.RequestBody;

import static com.example.home.tool.StaticActi.ip;

public class MeFragment extends Fragment {

    private View view;
    private ImageView pho_img;
    private TextView message;
    private TextView me_name;
    private LinearLayout me_info;
    private LinearLayout indent_info;
    private LinearLayout pasw_info;
    private LinearLayout opinion_info;
    private Button exit;
    private Content content;
    private RequestBody requestBody;
    private JSONObject jsonObject;
    private Handler handler;
    private Gson gson;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private Request request;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_me, container, false);

        initview();
        isLogin();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        updateUI();
    }

    private void isLogin() {
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("登录".equals(exit.getText())) {
                    // 跳转到登录界面
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    getActivity().startActivity(intent);
                } else if ("退出登录".equals(exit.getText().toString())) {
                    // 退出登录
                    logout();
                }
            }
        });
    }


    private void updateUI() {
        if (TextUtils.isEmpty(OKHttpTool.TOKEN)) {
            // 未登录状态
            clearUserData();
            exit.setText("登录");
            me_name.setText("请先登录");
        } else {
            // 已登录状态
            getUserData();
            exit.setText("退出登录");
        }
    }

    private void getUserData() {
        String url = "prod-api/api/common/user/getInfo";
        OKHttpTool.doNetRequest(url,
                OKHttpTool.GET,
                MeBean.class,
                new OKHttpTool.NetCallback() {
                    @Override
                    public void onSuccess(Object obj) {
                        MeBean userDataBean = (MeBean) obj;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (userDataBean.getCode() == 200) {
                                    Log.v("xhf", "执行了");
                                    bindSavaUser(userDataBean);
                                } else {
                                    clearUserData();
                                    me_name.setText("请先登录");
                                }
                            }
                        });
                    }

                    @Override
                    public void onFailure(String msg) {
                        // 处理请求失败的情况
                        Log.v("xhf", "执行失败"+msg);
                    }
                });
    }


    private void bindSavaUser(MeBean userDataBean) {

        PersonInfoUser.USERNAME = userDataBean.getUser().getNickName();

        PersonInfoUser.SEX = userDataBean.getUser().getSex();
        PersonInfoUser.PHONE = userDataBean.getUser().getPhonenumber();

        me_name.setText(userDataBean.getUser().getNickName());

        Glide.with(getActivity()).load(ip + userDataBean.getUser().getAvatar()).into(pho_img);

        me_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.v("xhf", "点击了");
                Intent intent = new Intent(MeFragment.this.getActivity(), MeInfoActivity.class);
                String userMeJson = gson.toJson(userDataBean);
                intent.putExtra("name", userMeJson);
                MeFragment.this.getActivity().startActivity(intent);
            }
        });
    }

    private void logout() {
        // 用户点击退出登录时的逻辑
        clearUserData();
        OKHttpTool.TOKEN = "";
        updateUI(); // 更新 UI 显示为未登录状态
    }

    private void initview() {

        jsonObject = new JSONObject();
        pho_img = view.findViewById(R.id.pho_img);
        message = view.findViewById(R.id.message);
        me_name = view.findViewById(R.id.me_name);
        me_info = view.findViewById(R.id.me_info);
        indent_info = view.findViewById(R.id.indent_info);
        pasw_info = view.findViewById(R.id.pasw_info);
        opinion_info = view.findViewById(R.id.opinion_info);
        exit = view.findViewById(R.id.exit);
        handler = new Handler();

        sharedPreferences = getActivity().getSharedPreferences("login", Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();


        pasw_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到修改密码页面
                Intent intent = new Intent(requireContext(), ChangePasswordActivity.class);
                startActivity(intent);
            }
        });

        indent_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到订单列表页面
                Intent intent = new Intent(requireContext(), OrderListActivity.class);
                startActivity(intent);
            }
        });

        opinion_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到订单列表页面
                Intent intent = new Intent(requireContext(), FeedBackActivity.class);
                startActivity(intent);
            }
        });
    }

    private void clearUserData() {
        // 清除本地存储的用户信息，例如 SharedPreferences 中的数据
        SharedPreferences preferences = requireContext().getSharedPreferences("user_data", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        OKHttpTool.TOKEN = "";
        editor.clear();
        editor.apply();
    }

}
